/**
 * API集成测试工具
 * 用于测试所有API接口的集成情况
 */

import { orderApi, teacherApi, deliveryApi, requirementApi, constants } from '../api'
import { handleApiResponse, formatTeacherData, formatOrderData } from './apiHelper'

/**
 * API测试结果收集器
 */
class ApiTestCollector {
  constructor() {
    this.results = []
    this.passed = 0
    this.failed = 0
  }

  addResult(testName, success, message, data = null) {
    this.results.push({
      testName,
      success,
      message,
      data,
      timestamp: new Date().toISOString()
    })

    if (success) {
      this.passed++
    } else {
      this.failed++
    }
  }

  getReport() {
    return {
      total: this.results.length,
      passed: this.passed,
      failed: this.failed,
      results: this.results
    }
  }

  printReport() {
    console.log('=== API集成测试报告 ===')
    console.log(`总测试数: ${this.results.length}`)
    console.log(`通过: ${this.passed}`)
    console.log(`失败: ${this.failed}`)
    console.log(`成功率: ${((this.passed / this.results.length) * 100).toFixed(2)}%`)
    
    console.log('\n详细结果:')
    this.results.forEach((result, index) => {
      const status = result.success ? '✅' : '❌'
      console.log(`${index + 1}. ${status} ${result.testName}: ${result.message}`)
    })
  }
}

/**
 * 教师API测试
 */
export const testTeacherApi = async (collector) => {
  console.log('开始测试教师相关API...')

  // 测试教师列表
  try {
    const response = await teacherApi.getTeacherList({
      current: 1,
      size: 5
    })
    
    if (response.code === '1000') {
      const teachers = response.result?.records || []
      collector.addResult(
        '教师列表API',
        true,
        `成功获取${teachers.length}条教师数据`,
        teachers
      )

      // 测试数据格式转换
      if (teachers.length > 0) {
        const formattedTeacher = formatTeacherData(teachers[0])
        const hasRequiredFields = formattedTeacher.id && formattedTeacher.name
        collector.addResult(
          '教师数据格式转换',
          hasRequiredFields,
          hasRequiredFields ? '数据格式转换成功' : '缺少必要字段',
          formattedTeacher
        )
      }
    } else {
      collector.addResult('教师列表API', false, response.message || 'API调用失败')
    }
  } catch (error) {
    collector.addResult('教师列表API', false, `网络错误: ${error.message}`)
  }

  // 测试教师详情（如果有教师ID）
  try {
    const response = await teacherApi.getTeacherDetail(1)
    collector.addResult(
      '教师详情API',
      response.code === '1000',
      response.code === '1000' ? '教师详情获取成功' : response.message || 'API调用失败'
    )
  } catch (error) {
    collector.addResult('教师详情API', false, `网络错误: ${error.message}`)
  }
}

/**
 * 订单API测试
 */
export const testOrderApi = async (collector) => {
  console.log('开始测试订单相关API...')

  // 测试学生端订单列表
  try {
    const response = await orderApi.getStudentOrderList({
      current: 1,
      size: 5,
      orderStatus: constants.STUDENT_ORDER_STATUS.WAITING_ACCEPT
    })
    
    if (response.code === '1000') {
      const orders = response.result?.records || []
      collector.addResult(
        '学生端订单列表API',
        true,
        `成功获取${orders.length}条订单数据`,
        orders
      )

      // 测试数据格式转换
      if (orders.length > 0) {
        const formattedOrder = formatOrderData(orders[0])
        const hasRequiredFields = formattedOrder.id && formattedOrder.orderNo
        collector.addResult(
          '订单数据格式转换',
          hasRequiredFields,
          hasRequiredFields ? '数据格式转换成功' : '缺少必要字段',
          formattedOrder
        )
      }
    } else {
      collector.addResult('学生端订单列表API', false, response.message || 'API调用失败')
    }
  } catch (error) {
    collector.addResult('学生端订单列表API', false, `网络错误: ${error.message}`)
  }

  // 测试教师端订单列表
  try {
    const response = await orderApi.getTeacherOrderList({
      current: 1,
      size: 5,
      delverStatus: constants.TEACHER_DELIVERY_STATUS.DELIVERING
    })
    
    collector.addResult(
      '教师端订单列表API',
      response.code === '1000',
      response.code === '1000' ? '教师端订单列表获取成功' : response.message || 'API调用失败'
    )
  } catch (error) {
    collector.addResult('教师端订单列表API', false, `网络错误: ${error.message}`)
  }
}

/**
 * 需求API测试
 */
export const testRequirementApi = async (collector) => {
  console.log('开始测试需求相关API...')

  // 测试需求列表
  try {
    const response = await requirementApi.getRequirementPage({
      current: 1,
      size: 5
    })
    
    collector.addResult(
      '需求列表API',
      response.code === '1000',
      response.code === '1000' ? '需求列表获取成功' : response.message || 'API调用失败'
    )
  } catch (error) {
    collector.addResult('需求列表API', false, `网络错误: ${error.message}`)
  }

  // 测试需求发布（使用测试数据）
  try {
    const testRequirement = {
      tutoringItem: constants.TUTORING_ITEM.HOMEWORK,
      studyStage: constants.STUDY_STAGE.UNDERGRADUATE,
      studyPlace: constants.STUDY_PLACE.DOMESTIC,
      studySchool: '测试大学',
      studyMajor: '测试专业',
      budgetMin: 1000,
      budgetMax: 2000,
      teacherLevel: constants.TEACHER_LEVEL.MASTER,
      teacherAbroad: constants.TEACHER_ABROAD.NO_REQUIREMENT,
      requirementText: '这是一个API测试需求',
      comment: '测试备注'
    }

    // 注意：这里只是测试API调用格式，实际测试时可能不想真的创建数据
    // const response = await requirementApi.addRequirement(testRequirement)
    
    collector.addResult(
      '需求发布API格式',
      true,
      '需求发布API参数格式正确',
      testRequirement
    )
  } catch (error) {
    collector.addResult('需求发布API格式', false, `参数格式错误: ${error.message}`)
  }
}

/**
 * 常量定义测试
 */
export const testConstants = (collector) => {
  console.log('开始测试常量定义...')

  const requiredConstants = [
    'TUTORING_ITEM',
    'STUDY_STAGE',
    'STUDY_PLACE',
    'TEACHER_LEVEL',
    'TEACHER_ABROAD',
    'STUDENT_ORDER_STATUS',
    'TEACHER_DELIVERY_STATUS',
    'GOOD_AT_ITEMS',
    'AUDIT_STATUS'
  ]

  requiredConstants.forEach(constantName => {
    const hasConstant = constants[constantName] !== undefined
    collector.addResult(
      `常量${constantName}`,
      hasConstant,
      hasConstant ? '常量定义正确' : '常量未定义'
    )
  })

  // 测试文本映射
  const textMappings = [
    'TUTORING_ITEM_TEXT',
    'STUDY_STAGE_TEXT',
    'TEACHER_LEVEL_TEXT',
    'GOOD_AT_ITEMS_TEXT'
  ]

  textMappings.forEach(mappingName => {
    const hasMapping = constants[mappingName] !== undefined
    collector.addResult(
      `文本映射${mappingName}`,
      hasMapping,
      hasMapping ? '文本映射定义正确' : '文本映射未定义'
    )
  })
}

/**
 * 运行完整的API集成测试
 */
export const runFullApiTest = async () => {
  const collector = new ApiTestCollector()
  
  console.log('开始API集成测试...')
  
  // 测试常量定义
  testConstants(collector)
  
  // 测试各个API模块
  await testTeacherApi(collector)
  await testOrderApi(collector)
  await testRequirementApi(collector)
  
  // 输出测试报告
  collector.printReport()
  
  return collector.getReport()
}

/**
 * 快速健康检查
 */
export const quickHealthCheck = async () => {
  console.log('执行API健康检查...')
  
  const checks = [
    {
      name: '教师列表API',
      test: () => teacherApi.getTeacherList({ current: 1, size: 1 })
    },
    {
      name: '学生端订单列表API',
      test: () => orderApi.getStudentOrderList({ current: 1, size: 1, orderStatus: 0 })
    }
  ]
  
  const results = []
  
  for (const check of checks) {
    try {
      const response = await check.test()
      results.push({
        name: check.name,
        status: response.code === '1000' ? 'OK' : 'FAIL',
        message: response.message || 'Success'
      })
    } catch (error) {
      results.push({
        name: check.name,
        status: 'ERROR',
        message: error.message
      })
    }
  }
  
  console.log('健康检查结果:', results)
  return results
}

export default {
  runFullApiTest,
  quickHealthCheck,
  testTeacherApi,
  testOrderApi,
  testRequirementApi,
  testConstants
}
